package com.cftpay.payexperience.usage.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cftpay.payexperience.R;
import com.cftpay.payexperience.usage.adapter.PayTypeAdapter;
import com.cftpay.payexperience.usage.util.NetworkUtil;
import com.cftpay.payexperience.usage.util.PayToastUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import sdk.pay.PayUtil;
import sdk.pay.listener.PayGetPayTypeListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.PayTypeModel;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayMD5Util;


public class PayActivity extends Activity implements PayUtilCallBack {
    private int mCheckedId = -1;
    private ImageView mImageCheckedIv;
    private ListView mPayListLv;
    private PayUtil mPayUtil;
    protected Dialog mProgressDialog;
    private TextView mPayMoneyTv;
    private static Activity mActivity;
    private String mOrder, mOrdertime;
    private Handler mHandler = new Handler();
    private static String mType;
    private String mSign;
    private static final String mGoodsPrice = "1.00";
    private static final String PAY_SDK = "paySdk";
    private String APPID = "";
    private String APP_KEY = "";
    private String KEY = "";
    private String VECTOR = "";
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            dismiss();
            final List<PayTypeModel> payTypeModelList = mPayUtil.getPayTypeModels();
            if (payTypeModelList.size() > 0) {
                mPayListLv.setVisibility(View.VISIBLE);
                PayTypeAdapter adapter = new PayTypeAdapter(PayActivity.this, payTypeModelList);
                mPayListLv.setAdapter(adapter);
                mPayListLv.post(new Runnable() {
                    // set default choice
                    @Override
                    public void run() {
                        if (mCheckedId == -1) {
                            for (PayTypeModel typeModel : payTypeModelList) {
                                if (typeModel.getTypeid().contains("ZFB")) {
                                    mCheckedId = mPayUtil.getPayTypeModels().indexOf(typeModel);
                                    break;
                                } else {
                                    mCheckedId = 0;
                                }
                            }
                        }
                        mImageCheckedIv = (ImageView) mPayListLv.getChildAt(mCheckedId).findViewById(R.id.image_checked);
                        mImageCheckedIv.setImageResource(R.drawable.icon_radio_button_yes);
                    }
                });
            } else {
                mPayListLv.setVisibility(View.GONE);
                PayToastUtil.showMessage(PayActivity.this, "Did not get the payment!");
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_layout);
        initWidgets();
        initPay();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.pay.close");
        localBroadcastManager.registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
    }

    public static void startActivity(Activity activity, String type) {
        Intent intent = new Intent(activity, PayActivity.class);
        mActivity = activity;
        mType = type;
        activity.startActivity(intent);
    }

    private void initPay() {
        selectPayParameters();
        mPayUtil = new PayUtil(mActivity, this, true);
        mPayUtil.setPayParam(APPID, KEY, VECTOR);
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        mOrder = mOrdertime = dateFormat.format(date);
        mSign = PayMD5Util.getMD5(
                APPID + "&" + mOrder + "&" + mGoodsPrice + "&"
                        + mOrdertime + "&" + APP_KEY);
        showDialog();
        getPayType();
    }

    private void selectPayParameters() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            PayActivity.this.deleteSharedPreferences(PAY_SDK);
        } else {
            SharedPreferences sharedPreferences = getSharedPreferences(PAY_SDK, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear().apply();
        }
        if ("2".equals(mType)) {
            //互扫
            APPID = "68017104468401";
            APP_KEY = "046809104855zn7jg7BQ";
            KEY = "c88c32450808790f013686a6fad53951";
            VECTOR = "8f433363501e2f2c";
        } else if ("3".equals(mType)) {
            //直接拉起支付
            APPID = "68017104468402";
            APP_KEY = "046809133157BYYw82Iv";
            KEY = "5730bd19e518ef28e7082013303b616a";
            VECTOR = "85479125eb94f924";
        }
    }

    private void getPayType() {
        if (NetworkUtil.isNetworkAvailable(this)) {
            mPayUtil.getPayType(getTokenParam(), new PayGetPayTypeListener() {
                @Override
                public void onPayDataResult() {
                    runOnUiThread(mRunnable);
                }
            });
        } else {
            dismiss();
            PayToastUtil.showMessage(this, getString(R.string.network_not_connected));
        }
    }

    private TokenParam getTokenParam() {
        String p1_appid = APPID;
        String p2_order = mOrder;
        String p3_money = mGoodsPrice;
        String p6_orderTime = mOrdertime;
        TokenParam tokenParam = new TokenParam();
        tokenParam.setP1_appid(p1_appid);
        tokenParam.setP2_orderNumber(p2_order);
        tokenParam.setP3_money(p3_money);
        tokenParam.setP6_orderTime(p6_orderTime);
        tokenParam.setP8_sign(mSign);
        return tokenParam;
    }

    private void initWidgets() {
        mPayListLv = (ListView) findViewById(R.id.lv_pay_list);
        Button submitBtn = (Button) findViewById(R.id.submit_pay_btn);
        mPayMoneyTv = (TextView) findViewById(R.id.tv_pay_money);
        mPayMoneyTv.setText(mGoodsPrice);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedId >= 0) {
                    showDialog();
                    String typeId = getTypeId(mCheckedId);
                    mSign = PayMD5Util.getMD5(APPID + "&" + mOrder + "&" +
                            mGoodsPrice + "&" + mOrdertime + "&" + typeId + "&" + APP_KEY);
                    mPayUtil.pay(typeId, getTokenParam());
                } else {
                    PayToastUtil.showMessage(PayActivity.this, "Payment has not yet chosen");
                }
            }
        });
        mPayListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mCheckedId != -1 && mImageCheckedIv != null) {
                    mImageCheckedIv.setImageResource(R.drawable.icon_radio_button_no);
                }
                mImageCheckedIv = (ImageView) view.findViewById(R.id.image_checked);
                mImageCheckedIv.setImageResource(R.drawable.icon_radio_button_yes);
                mCheckedId = position;
            }
        });
    }

    private String getTypeId(int index) {
        List<PayTypeModel> list = mPayUtil.getPayTypeModels();
        PayTypeModel model = list.get(index);
        return model.getTypeid();
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.show();
        } else {
            mProgressDialog = ProgressDialog.show(this, "",
                    getString(R.string.pay_info), false, true, null);
        }
    }

    @Override
    public void onPayException(String s) {
        dismiss();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 2500);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };


}